using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Models;
using System.Threading.Tasks;
using IDAL;

namespace DAL
{
    public class DeviceRecordService : IDeviceRecordService
    {
        private ITAMContext dbContext = null;
        public DeviceRecordService(ITAMContext context)
        {
            this.dbContext = context;
        }

        public async Task<int> AddDevice(DeviceRecord record)
        {
            dbContext.Entry(record).State = EntityState.Added;
            return await dbContext.SaveChangesAsync();
        }

        public async Task<int> UpdateDevice(DeviceRecord record)
        {
            dbContext.Attach(record).State = EntityState.Modified;
            return await dbContext.SaveChangesAsync();
        }

        public List<DeviceRecord> GetDevices(int pageNum, int pageSize)
        {
            return (from d in dbContext.DeviceRecords
                    join c in dbContext.DeviceCategories on d.CategoryId equals c.Id
                    orderby d.AssetNumber, d.Id ascending
                    select new DeviceRecord()
                    {
                        AssetNumber = d.AssetNumber,
                        CategoryId = d.CategoryId,
                        CategoryName = c.Name,
                        DepreciationRuleId = d.DepreciationRuleId,
                        DeleteAt = d.DeleteAt,
                        Description = d.Description,
                        ExpireDate = d.ExpireDate,
                        Id = d.Id,
                        Ip = d.Ip,
                        Mac = d.Mac,
                        Photo = d.Photo,
                        Price = d.Price,
                        State=d.State,
                        PurchaseChannelId = d.PurchaseChannelId,
                        PurchasedDate = d.PurchasedDate,
                        UpdatedAt = d.UpdatedAt,
                        VendorId = d.VendorId,
                        CreateAt = d.CreateAt
                    }).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
        }

        public DeviceRecord GetDeviceById(uint id)
        {
            var result = from d in dbContext.DeviceRecords where d.Id == id select d;
            return result.FirstOrDefault();
        }

        public bool DeviceExists(uint id)
        {
            return dbContext.DeviceRecords.Any(dr => dr.Id == id);
        }
    }
}